<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  reqAddTrademark,
  reqDeleteTrademark,
  reqGetTrademarkList,
  reqUpdateTrademark,
} from "@/api/product/trademark";
import type { Records, TradeMark } from "@/api/product/trademark/type.ts";
import { TradeMarkResponseData } from "@/api/product/trademark/type.ts";
import { ElMessage, UploadProps } from "element-plus";
import useUserStore from "@/store/modules/user.ts";

let userStore = useUserStore();
// 分页器相关属性
// 当前页码
let pageNo = ref(1);
// 每页显示条数 默认10条
let limit = ref(3);
// 每页可选的展示条数
let pageSizes = ref([1, 3, 5, 7]);
// 记录总条数
let total = ref(0);
// 表格数据
let tradeMarkArr = ref<Records>([]);
// dialog对话框
let dialogFormVisible = ref(false);
// 添加或者修改的表单数据
let title = ref("添加品牌");
let trademarkParams = reactive<TradeMark>({
  id: -1,
  tmName: "",
  logoUrl: "",
});

const formRef = ref();

// 钩子函数 挂载完成后获取表格数据
onMounted(() => {
  console.log(userStore.buttons);
  getList();
});

// 获取表格数据
const getList = async () => {
  let resultTrademarkList: TradeMarkResponseData = await reqGetTrademarkList(
    pageNo.value,
    limit.value,
  );
  if (resultTrademarkList.code == 200) {
    total.value = resultTrademarkList.data.total;
    tradeMarkArr.value = resultTrademarkList.data.records;
  }
};

// 分页器相关方法
// 每页显示条数改变时触发
const handleSizeChange = (val: number) => {
  // 重置当前limit
  limit.value = val;
  getList();
};

// 当前页码改变时触发
const handleCurrentChange = (val: number) => {
  // 重置当前页码
  pageNo.value = val;
  getList();
};

// 打开对话框
const openDialog = (row: any) => {
  title.value = row ? "修改品牌" : "添加品牌";
  // 如果是修改品牌，就把当前行的数据赋值给表单数据
  if (row) {
    // trademarkParams.id = row.id;
    // trademarkParams.tmName = row.tmName;
    // trademarkParams.logoUrl = row.logoUrl;
    Object.assign(trademarkParams, row);
  }
  dialogFormVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  // 如果校验失败，会返回一个失败的promise，后面的语句就不会执行了
  await formRef.value.validate();
  if (!(trademarkParams.id != -1)) {
    // 添加品牌
    let resultAddTrademark = await reqAddTrademark(trademarkParams);
    if (resultAddTrademark.code == 200) {
      ElMessage.success("添加品牌成功");
      resetForm();
      getList();
    } else {
      ElMessage.error(resultAddTrademark.message);
    }
  } else {
    // 修改品牌
    let resultUpdateTrademark = await reqUpdateTrademark(trademarkParams);
    if (resultUpdateTrademark.code == 200) {
      ElMessage.success("修改品牌成功");
      resetForm();
      getList();
    } else {
      ElMessage.error(resultUpdateTrademark.message);
    }
  }

  dialogFormVisible.value = false;
};

// 文件上传前置钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// 文件上传成功钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkParams.logoUrl = response.data;
  //  图片上传成功之后 清除表单校验文字
  formRef.value.clearValidate("logoUrl");
};

// 清空表单数据
const resetForm = () => {
  trademarkParams.id = -1;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  // 清除上一次的表单校验文字
  formRef.value.clearValidate();
};

// 关闭对话框
const close = () => {
  dialogFormVisible.value = false;
  resetForm();
};

// 表单校验函数
const checkTmName = (rule: any, value: any, callback: any) => {
  console.log(value);
  console.log(trademarkParams.tmName);
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error("品牌名称长度不能小于2个字符"));
    ElMessage.error("品牌名称长度不能小于2个字符");
  }
};

const checkLogoUrl = (rule: any, value: any, callback: any) => {
  if (value.trim().length > 0) {
    callback();
  } else {
    callback(new Error("品牌logo不能为空"));
    ElMessage.error("品牌logo不能为空");
  }
};

const rules = {
  tmName: [
    {
      required: true,
      message: "品牌名称不能为空",
      trigger: "blur",
      validator: checkTmName,
    },
  ],
  logoUrl: [
    { required: true, message: "品牌logo不能为空", validator: checkLogoUrl },
  ],
};

// 删除品牌
const removeTrademark = async (row: TradeMark) => {
  if (!row.id) {
    return ElMessage.error("删除品牌失败");
  }
  let resultDeleteTrademark: any = reqDeleteTrademark(row.id);
  if (resultDeleteTrademark.code == 200) {
    ElMessage.success("删除品牌成功");
    getList();
  } else {
    ElMessage.error(resultDeleteTrademark.message);
  }
  if (tradeMarkArr.value.length == 1 && pageNo.value > 1) {
    pageNo.value--;
  }
  getList();
};

defineOptions({
  name: "Trademark",
});
</script>

<template>
  <!--  表格显示模块 -->
  <el-card class="box-card">
    <!--  顶部添加品牌的按钮  -->
    <div>
      <el-button
        type="primary"
        v-has="`btn.Trademark.add`"
        icon="Plus"
        @click="openDialog(null)"
        >添加品牌
      </el-button>
    </div>
    <!--  表格  -->
    <div>
      <el-table :data="tradeMarkArr" border style="width: 100%">
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column prop="tmName" label="品牌名称" align="center" />
        <el-table-column prop="logoUrl" label="品牌logo" align="center">
          <template #default="{ row }">
            <img
              alt="品牌未添加图片"
              :src="row.logoUrl"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="品牌操作" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="edit"
              @click="openDialog(row)"
            ></el-button>
            <el-popconfirm
              :title="`去顶删除品牌${row.tmName}`"
              width="250px"
              @confirm="removeTrademark(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="delete">
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--  分页器组件  -->
    <div class="pagination_container">
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="pageSizes"
        :background="true"
        layout="prev, pager, next,jumper,sizes,->, total,"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </div>
  </el-card>
  <!--  dialog对话框  visible.sync  不会显示 但是使用v-model就没事  -->
  <el-dialog :title="title" v-model="dialogFormVisible" class="center-dialog">
    <!--    使用model可以  使用v-model就不行-->
    <el-form
      class="center-form"
      label-width="100px"
      :model="trademarkParams"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          placeholder="请输入品牌名称"
          style="width: 500px"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌logo" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/dev-api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer class="center-buttons">
      <el-button type="primary" @click="submitForm">确认</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.center-dialog {
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .center-buttons {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
